package financial

import (
	"net/http"
	"fmt"
	"io/ioutil"
	"encoding/json"
	"financial/db"
	"financial/db/entity"
	"os"
	"io"
)

/**
登录
 */
type Login struct {
	username string
	password string
}

/**
登录成功返回的json
 */
type LoginJson struct {
	Username string `json:"username"`
	RealName string `json:"realName"`
	Message  string `json:"message"`
}

/**
注册
 */
type Register struct {
	username string
	password string
	realName string
}

/**
注册成功返回的json
 */
type RegisterJson struct {
	Message string `json:"message"`
}

/**
记录用户费用
 */
type RecordFees struct {
	username      string
	dormitoryUuid string
	use           string
	money         float64
}

/**
读取用户费用
 */
type ReadFees struct {
	username      string
	dormitoryUuid string
	createTime    int64
	page          int
}

/**
 创建宿舍
 */
type CreateDormitory struct {
	dormitoryName   string
	owner           string
	members         string
	membersRealName string
	address         string
}

/**
更新宿舍信息
 */
type UpdateDormitory struct {
	dormitoryUuid   string
	members         string
	membersRealName string
	owner           string
}

/**
查看宿舍信息
 */
type QueryDormitory struct {
	owner string
}

/**
查询宿舍成功返回的json
 */
type QueryDormitoryJson struct {
	DormitoryList   []entity.DormitoryInfo `json:"dormitoryList"`
	Message string      `json:"message"`
}

type MessageJson struct {
	Message string      `json:"message"`
	State   int         `json:"state"`
	Data    interface{} `json:"data"`
}

func methods(req *http.Request, strings ...string) (map[string]interface{}, map[string]interface{}, map[string][]string) {
	var formValue map[string]interface{} = make(map[string]interface{}, 10)
	var bodyValue map[string]interface{}
	var headerValue map[string][]string

	//头参数
	headerValue = req.Header

	//表单参数
	for _, v := range strings {
		formValue[v] = req.Form.Get(v)
	}

	//实体类
	result, _ := ioutil.ReadAll(req.Body)
	defer req.Body.Close()
	var f interface{}
	json.Unmarshal(result, &f)
	bodyValue = f.(map[string]interface{})

	return formValue, bodyValue, headerValue
}

func login(rw http.ResponseWriter, req *http.Request) {
	req.ParseForm()
	//	fmt.Println(req.Method)
	login := new(Login)
	var headerValue map[string][]string
	var formValue map[string]interface{}
	var bodyValue map[string]interface{}
	var user entity.UserInfo
	if req.Method == "GET" {
		formValue, _, headerValue = methods(req, "username", "password")

		login.username = formValue["username"].(string)
		login.password = formValue["password"].(string)
	} else if req.Method == "POST" {

		_, bodyValue, headerValue = methods(req, "username", "password")

		login.username = bodyValue["username"].(string)
		login.password = bodyValue["password"].(string)

	}

	var isHeader bool = false
	for k, _ := range headerValue {
		if k == "financial-head-params" {
			isHeader = true
			break
		}
	}
	if !isHeader {

	} else {
		messageJson := MessageJson{
			State:   0,
			Message: "没有头参数",
		}
		b, _ := json.Marshal(messageJson)

		fmt.Fprintf(rw, string(b))
		return
	}
	if db.QueryUserData(login.username) != nil {
		user = db.EntityMap["userinfo"][login.username].(entity.UserInfo)
	} else {
		messageJson := MessageJson{
			State:   0,
			Message: "登录失败",
		}
		b, _ := json.Marshal(messageJson)

		fmt.Fprintf(rw, string(b))
		return
	}
	if len(user.Password) != 0 && login.password == user.Password {
		//返回真实姓名和账号
		loginJson := new(LoginJson)
		loginJson.RealName = user.RealName
		loginJson.Username = user.Username
		loginJson.Message = "登录成功"
		messageJson := MessageJson{
			State: 1,
			Data:  interface{}(*loginJson),
		}
		b, _ := json.Marshal(messageJson)

		fmt.Fprintf(rw, string(b))
	} else {
		messageJson := MessageJson{
			State:   0,
			Message: "登录失败",
		}
		b, _ := json.Marshal(messageJson)

		fmt.Fprintf(rw, string(b))
	}
}

func register(rw http.ResponseWriter, req *http.Request) {
	req.ParseForm()
	//	fmt.Println(req.Method)
	register := new(Register)
	var headerValue map[string][]string
	var bodyValue map[string]interface{}
	if req.Method == "POST" {

		_, bodyValue, headerValue = methods(req, "username", "password", "realName")

		register.username = bodyValue["username"].(string)
		register.password = bodyValue["password"].(string)
		register.realName = bodyValue["realName"].(string)
	}

	var isHeader bool = false
	for k, _ := range headerValue {
		if k == "financial-head-params" {
			isHeader = true
			break
		}
	}
	if !isHeader {

	} else {
		messageJson := MessageJson{
			State:   0,
			Message: "没有头参数",
		}
		b, _ := json.Marshal(messageJson)

		fmt.Fprintf(rw, string(b))
		return
	}
	isAre, isRegistered := db.WriteUser(register.username, register.password, register.realName)
	if isAre && !isRegistered {
		registerJson := new(RegisterJson)
		registerJson.Message = "注册成功"
		messageJson := MessageJson{
			State: 1,
			Data:  interface{}(*registerJson),
		}
		b, _ := json.Marshal(messageJson)

		fmt.Fprintf(rw, string(b))
	} else if isAre && isRegistered {
		messageJson := MessageJson{
			State:   0,
			Message: "该用户已经被注册",
		}
		b, _ := json.Marshal(messageJson)

		fmt.Fprintf(rw, string(b))
	}
}

func recordFees(rw http.ResponseWriter, req *http.Request) {
	req.ParseForm()
	recordFees := new(RecordFees)
	var headerValue map[string][]string
	var bodyValue map[string]interface{}
	if req.Method == "POST" {

		_, bodyValue, headerValue = methods(req, "username", "use", "money", "dormitoryUuid")

		recordFees.username = bodyValue["username"].(string)
		recordFees.use = bodyValue["use"].(string)
		recordFees.money = bodyValue["money"].(float64)
		recordFees.dormitoryUuid = bodyValue["dormitoryUuid"].(string)
	}

	var isHeader bool = false
	for k, _ := range headerValue {
		if k == "financial-head-params" {
			isHeader = true
			break
		}
	}

	if !isHeader {

	} else {
		messageJson := MessageJson{
			State:   0,
			Message: "没有头参数",
		}
		b, _ := json.Marshal(messageJson)

		fmt.Fprintf(rw, string(b))
		return
	}

	isCorrectWrite := db.WriteUserCost(recordFees.username, recordFees.use, recordFees.money, recordFees.dormitoryUuid)

	if isCorrectWrite {
		messageJson := MessageJson{
			State:   1,
			Message: "记录成功",
		}
		b, _ := json.Marshal(messageJson)

		fmt.Fprintf(rw, string(b))
	} else {
		messageJson := MessageJson{
			State:   1,
			Message: "记录失败",
		}
		b, _ := json.Marshal(messageJson)

		fmt.Fprintf(rw, string(b))
	}

}

func readFees(rw http.ResponseWriter, req *http.Request) {
	req.ParseForm()
	readFees := new(ReadFees)
	var headerValue map[string][]string
	var bodyValue map[string]interface{}
	if req.Method == "POST" {

		_, bodyValue, headerValue = methods(req, "username", "createTime", "page", "dormitoryUuid")

		readFees.username = bodyValue["username"].(string)
		readFees.createTime = bodyValue["createTime"].(int64)
		readFees.page = bodyValue["page"].(int)
		readFees.dormitoryUuid = bodyValue["dormitoryUuid"].(string)
	}

	var isHeader bool = false
	for k, _ := range headerValue {
		if k == "financial-head-params" {
			isHeader = true
			break
		}
	}

	if !isHeader {

	} else {
		messageJson := MessageJson{
			State:   0,
			Message: "没有头参数",
		}
		b, _ := json.Marshal(messageJson)

		fmt.Fprintf(rw, string(b))
		return
	}

	userCostSlice := db.QueryUserCostData(readFees.username, readFees.dormitoryUuid, readFees.createTime, readFees.page)
	messageJson := MessageJson{
		State:   1,
		Message: "查询成功",
		Data:    interface{}(userCostSlice),
	}
	b, _ := json.Marshal(messageJson)
	fmt.Fprintf(rw, string(b))

}

func createDormitory(rw http.ResponseWriter, req *http.Request) {
	req.ParseForm()
	createDormitory := new(CreateDormitory)
	var headerValue map[string][]string
	var bodyValue map[string]interface{}
	if req.Method == "POST" {

		_, bodyValue, headerValue = methods(req, "dormitoryName", "owner", "members", "membersRealName", "address")

		createDormitory.owner = bodyValue["owner"].(string)
		createDormitory.dormitoryName = bodyValue["dormitoryName"].(string)
		createDormitory.members = bodyValue["members"].(string)
		createDormitory.membersRealName = bodyValue["membersRealName"].(string)
		createDormitory.address = bodyValue["address"].(string)
	}

	var isHeader bool = false
	for k, _ := range headerValue {
		if k == "financial-head-params" {
			isHeader = true
			break
		}
	}

	if !isHeader {

	} else {
		messageJson := MessageJson{
			State:   0,
			Message: "没有头参数",
		}
		b, _ := json.Marshal(messageJson)

		fmt.Fprintf(rw, string(b))
		return
	}

	isCorrectWrite := db.WriteDormitoryInfo(createDormitory.dormitoryName, createDormitory.owner, createDormitory.members, createDormitory.membersRealName, len(createDormitory.members), createDormitory.address)

	if isCorrectWrite {
		messageJson := MessageJson{
			State:   1,
			Message: "创建成功",
		}
		b, _ := json.Marshal(messageJson)

		fmt.Fprintf(rw, string(b))
	} else {
		messageJson := MessageJson{
			State:   1,
			Message: "创建失败",
		}
		b, _ := json.Marshal(messageJson)

		fmt.Fprintf(rw, string(b))
	}

}

func updateDormitory(rw http.ResponseWriter, req *http.Request) {
	req.ParseForm()
	updateDormitory := new(UpdateDormitory)
	var headerValue map[string][]string
	var bodyValue map[string]interface{}
	if req.Method == "POST" {

		_, bodyValue, headerValue = methods(req, "dormitoryUuid", "owner", "members", "membersRealName")

		updateDormitory.owner = bodyValue["owner"].(string)
		updateDormitory.dormitoryUuid = bodyValue["dormitoryUuid"].(string)
		updateDormitory.members = bodyValue["members"].(string)
		updateDormitory.membersRealName = bodyValue["membersRealName"].(string)

	}

	var isHeader bool = false
	for k, _ := range headerValue {
		if k == "financial-head-params" {
			isHeader = true
			break
		}
	}

	if !isHeader {

	} else {
		messageJson := MessageJson{
			State:   0,
			Message: "没有头参数",
		}
		b, _ := json.Marshal(messageJson)

		fmt.Fprintf(rw, string(b))
		return
	}

	isCorrectWrite := db.UpdateDormitoryInfo(updateDormitory.dormitoryUuid, updateDormitory.members, updateDormitory.membersRealName, len(updateDormitory.members), updateDormitory.owner)

	if isCorrectWrite {
		messageJson := MessageJson{
			State:   1,
			Message: "更新成功",
		}
		b, _ := json.Marshal(messageJson)

		fmt.Fprintf(rw, string(b))
	} else {
		messageJson := MessageJson{
			State:   1,
			Message: "更新失败",
		}
		b, _ := json.Marshal(messageJson)

		fmt.Fprintf(rw, string(b))
	}
}

func queryDormitory(rw http.ResponseWriter, req *http.Request) {
	req.ParseForm()
	queryDormitory := new(QueryDormitory)
	var headerValue map[string][]string
	var bodyValue map[string]interface{}
	if req.Method == "POST" {

		_, bodyValue, headerValue = methods(req, "owner")

		queryDormitory.owner = bodyValue["owner"].(string)

	}

	var isHeader bool = false
	for k, _ := range headerValue {
		if k == "financial-head-params" {
			isHeader = true
			break
		}
	}

	if !isHeader {

	} else {
		messageJson := MessageJson{
			State:   0,
			Message: "没有头参数",
		}
		b, _ := json.Marshal(messageJson)

		fmt.Fprintf(rw, string(b))
		return
	}

	dormitoryInfoSlice := db.QueryDormitoryInfoData(queryDormitory.owner)

	if dormitoryInfoSlice != nil {

		queryDormitoryJson  := new(QueryDormitoryJson)
		queryDormitoryJson.Message ="查询成功"
		queryDormitoryJson.DormitoryList = dormitoryInfoSlice

		messageJson := MessageJson{
			State:   1,
			Data: interface{}(queryDormitoryJson),
		}
		b, _ := json.Marshal(messageJson)

		fmt.Fprintf(rw, string(b))
	} else {
		messageJson := MessageJson{
			State:   1,
			Message: "查询失败",
		}
		b, _ := json.Marshal(messageJson)

		fmt.Fprintf(rw, string(b))
	}
}

/**
设置静态目录
 */
func setStaticDirectory() {
	fsh := http.FileServer(http.Dir("D:\\Golang\\GoglandProjects\\files\\avatar\\"))
	http.Handle("/clientReqDownFile/", http.StripPrefix("/clientReqDownFile/", fsh))
}

func uploadFile(w http.ResponseWriter, r *http.Request) {
	r.ParseMultipartForm(32 << 20)
	file, handler, err := r.FormFile("uploadfile")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer file.Close()
	f, err := os.OpenFile("D:\\Golang\\GoglandProjects\\files\\avatar\\"+handler.Filename, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, os.ModePerm)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer f.Close()
	io.Copy(f, file)
	fmt.Fprintln(w, "upload ok!")
}


func Service() {
	http.HandleFunc("/login", login)
	http.HandleFunc("/register", register)
	http.HandleFunc("/recordFees", recordFees)
	http.HandleFunc("/readFees", readFees)
	http.HandleFunc("/createDormitory", createDormitory)
	http.HandleFunc("/updateDormitory", updateDormitory)
	http.HandleFunc("/queryDormitory", queryDormitory)
	setStaticDirectory()
	http.HandleFunc("/uploadFile", uploadFile)
	http.ListenAndServe(":4000", nil)
}
